{% extends 'sales/base.html' %}
{% load static %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'common:doc_list' %}">Documents</a></li>
    <li class="breadcrumb-item">{% if doc_obj %}Edit{% else %}Create{% endif %}</li>
  </ol>
</nav>
{% endblock breadcrumb %}
{% block content %}
<form id="add_form" method="POST" enctype="multipart/form-data" action="" novalidate>
  <div class="overview_form_block row marl justify-content-center">
    <div class="col-md-6">
      <div class="card">
        <div class="card-body">
          <div class="card-title text-center">
            {% if doc_obj %}EDIT{% else %}CREATE{% endif %} DOCUMENT
          </div>
          <div class="row marl">
            <div class="col-md-12">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="id_firstname">Title {% if doc_form.title.field.required %}<span class="error_marker"
                      style="color:red">*</span>{% endif %}</label>
                  <input type="text" id="title" class="form-control" name="title"
                    value="{% if doc_obj %}{{ doc_obj.title }}{% else %}{{request.POST.title}}{% endif %}"
                    placeholder="Document title">
                </div>
                <span class="error" id="id_title">{{ errors.title }}</span>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Upload Document {% if doc_form.document_file.field.required %}<span
                      class="error_marker" style="color:red">*</span>{% endif %}</label>
                  <input type="file" name="document_file" class="form-control" id="document_file" />
                </div>
                {% if doc_obj %}<span>{{doc_file_name}}</span>{% endif %}
                <span class="error" id="id_document_file">{{ errors.document_file }}</span>
              </div>
              {% if request.user.is_superuser or request.user.role == 'ADMIN' %}
              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus">Teams {% if doc_form.teams.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <select name="teams" id="id_teams" class="assigned_users form-control" multiple>
                    {% for team in teams %}
                    <option data-users="{{team.get_users}}" value="{{team.id}}" {% if team in doc_obj.teams.all %}
                      selected="" {% endif %}>
                      {{team}}</option>
                    {% endfor %}
                  </select>
                  <span class="error" id="id__teams">{{ doc_form.teams.errors }}</span>
                </div>
              </div>

              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus"><span class="">Users</span></label>
                  <select name="" aria-readonly="true" id="_id_assigned_to" class=" form-control" multiple>
                    {% if doc_obj and doc_obj.teams.all %}
                    {% for user in users %}
                    {% if user in doc_obj.get_team_users %}
                    <option value="{{user.id}}" selected="">{{user.email}}</option>
                    {% else %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    {% for user in users %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endfor %}
                    {% endif %}
                  </select>
                </div>
              </div>

              {% endif %}
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Share To{% if doc_form.shared_to.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <select class="assigned_users form-control" name="shared_to" multiple="multiple" id="id_assigned_to">
                    {% for user in users %}
                    {% if user != request.user %}
                    <option value="{{user.id}}" {% if user in doc_obj.get_assigned_users_not_in_teams or user.id in sharedto_list %}
                      selected="" {% endif %}>{{user.email}}</option>
                    {% endif %}
                    {% endfor %}
                  </select>
                  {{ errors.shared_to.errors }}
                </div>
              </div>
              <p></p>
              {% if doc_obj %}
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="id_status">Status{% if doc_form.status.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ doc_form.status }}
                  <span class="error">{{ doc_form.status.errors }}</span>
                </div>
              </div>
              {% endif %}
            </div>
          </div>
          <div class="row marl buttons_row form_btn_row text-center">
            <button class="btn btn-default save" type="submit" id="submit_btn">Save</button>
            <a href="{% url 'common:doc_list' %}" class="btn btn-default clear" id="create_doc_cancel">Cancel</a>

          </div>

        </div>
      </div>
    </div>
  </div>
</form>

<div class="row marl justify-content-center text-center mt-5 mb-5" id="progress_bar">
  
  <div class="progress position-relative" style="width:40%;height:1.5rem;">
    <span class="justify-content-center d-flex position-absolute w-100 percent">0%</span>
    <div class="progress-bar bar"></div>
  </div>
</div>

{% endblock content %}
{% block js_block %}
<script type="text/javascript">

  $(document).ready(function () {
    $('.assigned_users').select2();
    $('#id_teams').select2();
    $('#_id_assigned_to').select2({ disabled: 'readonly' });
  });

  var bar = $('.bar');
  var percent = $('.percent');

  $('#progress_bar').hide()

  $('form#add_form').ajaxForm({
    type: 'POST',
    dataType: 'json',
    url: ".",
    data: $('#add_form').serialize(),
    beforeSubmit: disableButton,
    beforeSend: function () {
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    uploadProgress: function (event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal);
      if (percentVal == '100%') {
        percent.html('Uploading ...')
      }
      else {
        percent.html(percentVal);
      }
    },
    success: function (data) {
      if (data.error) {
        $('.error').html('')
        $('.progress').hide()
        for (var key in data.errors) {
          $('#id_' + key).html("<p>" + data.errors[key][0] + "</p>");
        };
        $('#submit_btn').removeAttr('disabled')
      }
      else {
        $('.progress').show()
        window.location = data.success_url;
      }
    }
  });


  $('#submit_btn').click(function () {
    var file = $('#document_file')[0].files[0].name;
    console.log(file)
    if ($('#title').val().length > 0 && file.length > 0) {
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
      $('#progress_bar').show()
    }

  });

  function disableButton() {
    // $('#progress_bar').show()
    $('#submit_btn').attr('disabled', 'disabled')
  }

  function find_dict(dict, id){
    var index = dict.map(function(o) { return o.team; }).indexOf(parseInt(id));
    return dict[index]['users']
  }

  $("#id_teams").change(function (e) {
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'common:get_teams_and_users' %}", function(data){
      // console.log(data)
          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        $('#id_assigned_to').select2().trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          // console.log("s_users", selected_users)
          var un_select_users = [].concat.apply([], selected_users)
          // console.log('un select users', un_select_users);


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
            // console.log(' selected', $(this).attr('data-users').split(','))
            // console.log('selected', $(this).attr('data-users'))
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
            // console.log('un selected', $(this).attr('data-users').split(','))
          }
        });
        // console.log('selected users teams data', users)
        var existingUsers = $('#id_assigned_to').val();
        var allUsers = users
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });

  $(document).ready(function($) {

    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'common:get_teams_and_users' %}", function(data){

          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        // $('#id_assigned_to').select2().val([]).trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          var un_select_users = [].concat.apply([], selected_users)


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            // $(this).attr('disabled', 'disabled')
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
          }
        });
        var existingUsers = $('#id_assigned_to').val();
        // var allUsers = users.concat(existingUsers)
        var allUsers = users
        // console.log(existingUsers)
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });
</script>
{% endblock js_block %}